<template>
  <el-scrollbar class="h-full">
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formState"
      :rules="rules"
      class="mb-6"
      label-position="top"
      require-asterisk-position="right"
    >
      <QuoteCard>
        <el-form-item label="添加域名时批量添加记录">
          <BasicSwitch v-model="rrsSwitch" />
        </el-form-item>
        <LogInputTable
          v-if="rrsSwitch === 1"
          label="默认批量添加记录类型"
          :form-state="formState"
          is-disabled-value
        />
        <div class="-ml-2">
          <el-divider></el-divider>
          <el-button type="primary" @click="handleSave">保存配置</el-button>
        </div>
      </QuoteCard>
    </el-form>
  </el-scrollbar>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { cloneDeep } from 'lodash-es'

import ToastUtils from '@/utils/toast'

import LogInputTable from '../../user/domain/components/LogInputTable.vue'
import type { RrsItem } from '../../user/domain/type'
import { useDomainAddRules } from '../../user/domain/utils/rules/domainAdd'

const loading = ref(false)
const rrsSwitch = ref(1)
const formRef = ref<FormInstance>()
const rrsCache = ref<RrsItem[]>([])

const formState = reactive({
  rrs: [] as RrsItem[]
})
const { rules } = useDomainAddRules(formState, formRef, true)

const getConfig = () => {
  loading.value = true
  configInfoApi({ key: ['feature'] })
    .then(res => {
      const data = res.feature!
      rrsSwitch.value = data.domain_add_show_rrs_switch!
      formState.rrs = data.default_rrs!
      rrsCache.value = cloneDeep(data.default_rrs!)
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  getConfig()
})

const handleSave = async () => {
  await formRef.value?.validateField('rrsMain')
  await formRef.value?.validate()

  loading.value = true
  try {
    await editConfigApi({
      feature: {
        domain_add_show_rrs_switch: rrsSwitch.value,
        default_rrs:
          rrsSwitch.value === 1
            ? formState.rrs.map(v => ({
                ...v,
                name: v.name?.trim() || '@'
              }))
            : rrsCache.value
      }
    })
    ToastUtils.success('保存成功')
    getConfig()
  } finally {
    loading.value = false
  }
}

// provide('formRef', formRef)
provide('isDisabledValue', true)
</script>

<style lang="scss" scoped>
.el-radio {
  height: 20px;
}
:deep(.el-form-item__label) {
  pointer-events: none;
}
</style>
